package base.thread_JUC2.chapter03.demo04;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

@Slf4j
public class SearcherRunnable implements Runnable{
    private int firstRow;//矩阵部分起始位置
    private int lastRow;//矩阵部分截止位置
    private MatrixMock matrixMock;//矩阵
    private Results results;//存储结果的数组
    private int number;//查找的数字
    private final CyclicBarrier cyclicBarrier;//CyclicBarrier来控制执行

    public SearcherRunnable(int firstRow, int lastRow, MatrixMock matrixMock, Results results, int number, CyclicBarrier cyclicBarrier){
        this.firstRow = firstRow;
        this.lastRow = lastRow;
        this.matrixMock = matrixMock;
        this.results = results;
        this.number = number;
        this.cyclicBarrier = cyclicBarrier;
    }

    /**
     * 每个线程都计算查找到的 number 的计数
     */
    @Override
    public void run() {
        int counter;
        System.out.printf("%s: Processing lines from %d to %d.\n",Thread.currentThread().getName(),firstRow,lastRow);
        for (int i = firstRow; i < lastRow; i++) {
            int[] row = matrixMock.getRow(i);
            counter = 0;
            for (int j = 0; j < row.length; j++) {
                if (row[j]==number) {
                    counter++;
                }
            }
            results.setData(i, counter);
        }
        System.out.printf("%s: Lines processed.\n",Thread.currentThread().getName());

        try {
            cyclicBarrier.await();
        } catch (InterruptedException e) {
            log.info("-----------打断----InterruptedException----------");
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            log.info("-----------破坏了的----BrokenBarrierException----------");
            e.printStackTrace();
        }
    }
}
